/**
 * API服务基础配置
 */

import axios from 'axios';
import type { AxiosInstance, AxiosResponse } from 'axios';
import { messageError } from '../utils/notification';
import { requestDebugger } from '../utils/requestDebugger';

// 创建axios实例
const api: AxiosInstance = axios.create({
  baseURL: `${import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000'}/api`,
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    // 记录请求用于调试
    requestDebugger.logRequest(
      config.url || '',
      config.method || 'GET',
      config.params,
      config.data
    );

    // 添加认证令牌
    const authData = localStorage.getItem('auth_token');
    if (authData) {
      try {
        const tokenData = JSON.parse(authData);
        if (tokenData.access_token && config.headers) {
          config.headers.Authorization = `Bearer ${tokenData.access_token}`;
        }
      } catch (error) {
        console.warn('解析认证令牌失败:', error);
      }
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response: AxiosResponse) => {
    const { data } = response;

    // 如果响应包含success字段且为false，显示错误信息
    if (data.success === false) {
      messageError(data.message || '请求失败');
      return Promise.reject(new Error(data.message || '请求失败'));
    }

    return response;
  },
  async (error) => {
    // 处理HTTP错误状态码
    if (error.response) {
      const { status, data } = error.response;

      switch (status) {
        case 400:
          messageError(data.detail || data.message || '请求参数错误');
          break;
        case 401:
          // 处理认证失败
          if (error.config.url?.includes('/auth/refresh')) {
            // 刷新令牌失败，清除认证信息并跳转登录
            localStorage.removeItem('auth_token');
            localStorage.removeItem('user_info');
            localStorage.removeItem('user_permissions');
            window.location.href = '/login';
          } else {
            // 尝试刷新令牌
            try {
              const authData = localStorage.getItem('auth_token');
              if (authData) {
                const tokenData = JSON.parse(authData);
                if (tokenData.refresh_token) {
                  const refreshResponse = await api.post('/auth/refresh', {
                    refresh_token: tokenData.refresh_token
                  });

                  const newTokenData = refreshResponse.data.data;
                  const updatedToken = {
                    ...tokenData,
                    access_token: newTokenData.access_token,
                    expires_at: Date.now() + newTokenData.expires_in * 1000
                  };

                  localStorage.setItem('auth_token', JSON.stringify(updatedToken));

                  // 重试原请求
                  error.config.headers.Authorization = `Bearer ${newTokenData.access_token}`;
                  return api.request(error.config);
                }
              }
            } catch (refreshError) {
              // 刷新失败，清除认证信息
              localStorage.removeItem('auth_token');
              localStorage.removeItem('user_info');
              localStorage.removeItem('user_permissions');
              window.location.href = '/login';
            }
          }
          messageError('认证失败，请重新登录');
          break;
        case 403:
          messageError(data.detail || data.message || '权限不足');
          break;
        case 404:
          messageError(data.detail || data.message || '请求的资源不存在');
          break;
        case 422:
          // 处理验证错误，确保有有效的错误消息
          let errorMessage = '请求参数验证失败';
          if (data.detail) {
            if (Array.isArray(data.detail)) {
              errorMessage = data.detail.map((err: any) => err.msg || err.message || '验证失败').join(', ');
            } else if (typeof data.detail === 'string') {
              errorMessage = data.detail;
            }
          } else if (data.message) {
            errorMessage = data.message;
          }
          messageError(errorMessage || '请求参数验证失败');
          break;
        case 500:
          messageError(data.detail || data.message || '服务器内部错误');
          break;
        default:
          messageError(data.detail || data.message || `请求失败 (${status})`);
      }
    } else if (error.request) {
      // 处理网络错误
      if (error.code === 'ECONNABORTED') {
        messageError('请求超时，请检查网络连接或稍后重试');
      } else if (error.code === 'NETWORK_ERROR') {
        messageError('网络连接失败，请检查网络设置');
      } else {
        messageError('网络连接失败，请检查后端服务是否正常运行');
      }
    } else {
      messageError('请求配置错误');
    }

    return Promise.reject(error);
  }
);

export default api;
